package iterables;

import java.util.*;

public class IterablesOrdenadosAlternativo<T> implements Iterable <T>{
	  private Iterable<T> ite1;
	  private Iterable<T> ite2;
	  private Comparator<T> comp;

	  public IterablesOrdenadosAlternativo(Iterable<T> it1, Iterable<T> it2, 					   	            Comparator<T> cp) {
		this.ite1 = it1;
		this.ite2 = it2;
		this.comp = cp;
	  }
	  public Iterator<T> iterator(){
		return new IteradorOrdenados(ite1,ite2,comp);
	  }
	  private class IteradorOrdenados implements Iterator<T>{
			
			private Iterator<T> it1;
			private Iterator<T> it2;
			private Comparator<T> cp;

			private T st1;
			private T st2;
			private T s= null;
			public IteradorOrdenados(Iterable<T> ite1, Iterable<T> ite2, Comparator<T> cp){
				this.cp = cp;
				it1=ite1.iterator();
				it2=ite2.iterator();
				if(it1.hasNext()&& it2.hasNext()){
					st1 = it1.next();
					st2 = it2.next();
				}else if(it1.hasNext()&& !it2.hasNext()){
						st1 = it1.next();
				}else if(it2.hasNext()&& !it1.hasNext()){
						st2 = it2.next();
				}
			}
		
			public boolean hasNext() {
				return  st1 !=null || st2 != null;
			}

			public T next() {
				if(it1.hasNext()&& it2.hasNext()){
					if(cp.compare(st1,st2)<=0){ 
						s = st1;
						st1 = it1.next();
					}else{
						s = st2;
						st2 = it2.next();
					}
				}else if(it1.hasNext()&& !it2.hasNext()){
					if(st2 != null && cp.compare(st2,st1)<=0){
						s=st2;
						st2 = null;
					}else {
						s = st1;
						st1 = it1.next();
					}
				}else if(it2.hasNext()&& !it1.hasNext()){
					if(st1 != null && cp.compare(st1,st2)<=0){
						s=st1;
						st1 = null;
					}else {
						s = st2;
						st2 = it2.next();
					}
				}else if(!it2.hasNext()&& !it1.hasNext()){
					if (st1 != null && st2 != null){
						if(cp.compare(st1,st2)<=0){
							s=st1;
							st1 = null;
						}else {
							s = st2;
							st2 = null;
						}
					}else if(st1 != null){
							s=st1;
							st1 = null;
					}else{
							s=st2;
							st2 = null;
					
					}
				}
				return s;
			}
			public void remove() {		
			}	
		}	
	}

